package br.com.dips.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.math.NumberUtils;

import br.com.dips.model.Organizacao;
import br.com.dips.service.OrganizacaoService;

@Named
public class OrganizacaoConverter implements Converter {
	
	@Inject
	private OrganizacaoService orgService;

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value instanceof Organizacao) {
            return ((Organizacao) value).getId().toString();
        } else {
            return null;
        }
    }

	@Override
	public Object getAsObject(FacesContext context, UIComponent component, String value) {
		if (NumberUtils.isNumber(value)) { // NumberUtils do commons-lang
			Integer id = new Integer(value);
			Organizacao organizacao = orgService.consultar(id);
			return organizacao;
		} else {
			return null;
		}
	}

}
